/**
 * 
 */
package scriptrunner.execution;

import java.io.Serializable;
import java.util.ArrayList;

/**
 * @author Administrator
 * 
 */
public class ValueListObject extends ValueObject implements Serializable,
		Cloneable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3925390594016933158L;

	/**
	 * 
	 */
	public ValueListObject() {
		valueList = new ArrayList<ValueObject>();
	}

	private ArrayList<ValueObject> valueList;
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see scriptrunner.execution.ValueObject#clone()
	 */
	@Override
	public ValueListObject clone() throws CloneNotSupportedException {
		ValueListObject o = (ValueListObject) super.clone();
		o.valueList = new ArrayList<ValueObject>();
		for (ValueObject e : valueList)
			o.valueList.add(e.clone());
		return o;
	}

	/**
	 * @param idx
	 * @return
	 * @throws ExecuteErrorException
	 */
	public ValueObject GetListElement(ValueObject idx)
			throws ExecuteErrorException {
		if (!(idx instanceof ValueIntegerObject))
			throw (new ExecuteErrorException("The index should be an Integer"));
		
		int idxValue = ((ValueIntegerObject) idx).GetValue() ;
		if ( idxValue < 0 || idxValue >= valueList.size() )
			throw (new ExecuteErrorException("Index out of range"));
		
		return valueList.get(idxValue);
	}

	/**
	 * @param idx
	 * @param vo
	 * @throws ExecuteErrorException
	 */
	public void SetListElement(ValueObject idx, ValueObject vo)
			throws ExecuteErrorException, CloneNotSupportedException {
		if (!(idx instanceof ValueIntegerObject))
			throw (new ExecuteErrorException("The index should be an Integer"));
		
		int idxValue = ((ValueIntegerObject) idx).GetValue() ;
		if ( idxValue < 0 || idxValue >= valueList.size() )
			throw (new ExecuteErrorException("Index out of range"));
		
		valueList.set(idxValue, vo.clone() );
	}

	/**
	 * @param vo
	 * @throws CloneNotSupportedException
	 */
	public void AddListElement(ValueObject vo)
			throws CloneNotSupportedException {
		valueList.add(vo.clone());
	}
	
	public int GetElementCount() {
		return valueList.size();		
	}
	
	public boolean equals( Object o) {
		if ( o == null || ! (o instanceof ValueListObject ) )
			return false;
		
		return valueList.equals( ((ValueListObject)o).valueList);
	}

	public String toString() {
		String content = new String();
		
		for ( int i = 0; i < valueList.size(); ++i ) {
			String element = valueList.get(i).toString();
			if (i == 0)
				content += element;
			else
				content += "," + element;
		}
		
		return "[" + content + "]";
	}
}
